package com.zhou.cloud.controller;

import com.zhou.cloud.dao.entity.Dept;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zhouyongjun
 * @Description:
 * @date 2021/4/6 17:08
 */
@RestController
@RequestMapping("/consumer/dept")
@Log
@RefreshScope // 自动刷新机制
public class ConsumerController {
    @Autowired
    @Qualifier("restTemplate")
    RestTemplate restTemplate;
    static String URL = "http://provider/dept";

    // 负载均衡获取我们实际要访问的项目地址
    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("/get/{id}")
    public Dept getDept(@PathVariable("id") Long id) {
        log.info("get id="+id);
        return restTemplate.getForObject(URL+"/get/"+id,Dept.class);
    }
    @GetMapping("/list1")
    public List<Dept> listDept() {
        log.info("listDept");
        return restTemplate.getForObject(URL+"/list",List.class);
    }

    /**
    * @Description: 使用 loadBalancerClient来获取访问地址
    * @Params:
    * @Returns:
    * @Author: zhouyongjun
    * @Date Created in 2022/9/7 11:44
     */
    @GetMapping("/list2")
    public String listDept2() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("provider");
        String path = String.format("http://%s:%d/list",serviceInstance.getServiceId(),serviceInstance.getPort());
        return restTemplate.getForObject(URL+"/list",String.class);
    }


    @GetMapping("test")
    public String test() {
        return restTemplate.getForObject(URL+"/test",String.class);
    }




}
